package com.baor.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baor.dao.EquipmentDao;
import com.baor.dao.Removal_recordDao;
import com.baor.dao.UserDao;
import com.baor.domain.Equipment;
import com.baor.domain.RemovalRecordVO;
import com.baor.service.AddWorkOrderService;
import com.baor.util.R;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Service
public class AddWorkOrderServiceImpl implements AddWorkOrderService {


    @Autowired
    private EquipmentDao equipmentDao;

    @Autowired
    private Removal_recordDao removal_recordDao;

    @Autowired
    private UserDao userDao;



    @Override
    public R addWorkOrder(Map<String, Object> params) {

        String equipmentCode = params.get("code").toString().trim();

        String userId = params.get("userId").toString();


//        UserVO userVo = userDao.selectById(params.get("userId").toString());
//        String nickname = userVo.getNickname();
//        String phone = userVo.getPhone();


        // 根据设备编码查询设备
        Equipment equipment = equipmentDao.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Equipment>()
                        .eq(Equipment::getCode, equipmentCode)
        );
        if (equipment == null) {
            return R.er("未找到对应的设备信息");
        }

        // 添加清运记录到removal_record表
        RemovalRecordVO removalRecord = new RemovalRecordVO();
        // 生成工单号：XQ+年月日时分秒
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String workOrderNo = "XQ" + LocalDateTime.now().format(formatter);
        removalRecord.setClearanceWorkOrder(workOrderNo);
        // 设置设备ID
        removalRecord.setEquipmentId(equipment.getId().longValue());
        // 设置清运重量（转换为double类型）
        removalRecord.setWeight(equipment.getNowWeight().doubleValue());
        removalRecord.setResult(0);
        // 设置清运时间
        removalRecord.setRemovalTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        removalRecord.setWorkerId(Long.valueOf(userId));
//        removalRecord.setPhone(phone);
//        removalRecord.setNickname(nickname);

        int recordRows = removal_recordDao.insert(removalRecord);
        if (recordRows <= 0) {
            // 此处可根据业务需求决定是否回滚设备重量更新操作
            throw new RuntimeException("清运记录保存失败");
        }
        return R.ok("清运工单生成，工单号："+workOrderNo);
    }

    @Override
    public R addWorkOrderList(Map<String, Object> params) {
        try{
            int pageIndex = params.get("pageIndex") != null ? Integer.parseInt(params.get("pageIndex").toString()) : 1;
            int pageSize = params.get("pageSize") != null ? Integer.parseInt(params.get("pageSize").toString()) : 10;
            // 构建分页对象 - 注意这里修改了泛型类型为Map<String, Object>
            Page<Map<String, Object>> page = new Page<>(pageIndex, pageSize);
            // 构建联表查询条件
            MPJLambdaWrapper<RemovalRecordVO> wrapper = new MPJLambdaWrapper<>();
            wrapper.selectAll(RemovalRecordVO.class)
                    .select(Equipment::getCode, Equipment::getAddress,Equipment::getNowWeight)
                    .leftJoin(Equipment.class, Equipment::getId, RemovalRecordVO::getEquipmentId)
                    .orderByDesc(RemovalRecordVO::getRemovalTime)
                    .eq(RemovalRecordVO::getResult, 0);
            IPage<Map<String, Object>> resultPage = removal_recordDao.selectJoinMapsPage(page, wrapper);
            // 封装结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", resultPage.getRecords());
            result.put("totalSize", resultPage.getTotal());
            result.put("pageIndex", pageIndex);
            result.put("pageSize", pageSize);
            return R.ok(result);
        }catch (Exception e){
            e.printStackTrace();
            return R.er("查询清运工单失败: " + e.getMessage());
        }

    }

    @Override
    public R WorkOrderHistoryList(Map<String, Object> params) {
        try{
            int pageIndex = params.get("pageIndex") != null ? Integer.parseInt(params.get("pageIndex").toString()) : 1;
            int pageSize = params.get("pageSize") != null ? Integer.parseInt(params.get("pageSize").toString()) : 10;
            // 构建分页对象 - 注意这里修改了泛型类型为Map<String, Object>
            Page<Map<String, Object>> page = new Page<>(pageIndex, pageSize);
            // 构建联表查询条件
            MPJLambdaWrapper<RemovalRecordVO> wrapper = new MPJLambdaWrapper<>();
            wrapper.selectAll(RemovalRecordVO.class)
                    .select(Equipment::getCode, Equipment::getAddress,Equipment::getNowWeight)
                    .leftJoin(Equipment.class, Equipment::getId, RemovalRecordVO::getEquipmentId)
                    .orderByDesc(RemovalRecordVO::getRemovalTime)
                    .eq(RemovalRecordVO::getResult, 1);
            IPage<Map<String, Object>> resultPage = removal_recordDao.selectJoinMapsPage(page, wrapper);
            // 封装结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", resultPage.getRecords());
            result.put("totalSize", resultPage.getTotal());
            result.put("pageIndex", pageIndex);
            result.put("pageSize", pageSize);
            return R.ok(result);
        }catch (Exception e){
            e.printStackTrace();
            return R.er("查询清运工单，历史记录失败: " + e.getMessage());
        }

    }


}
